package com.zzh.bc.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.zzh.bc.log.log;
import com.zzh.bc.modules.oss.FileType;
import jakarta.servlet.ServletContext;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

public class FileManager {
    /**
     * 文件存储路径
     */
    public static final String FILE_ROOT_PATH = System.getProperty("user.dir") + File.separator + "file";

    public static String getPublicProjectPath(ServletContext sc) {
        return sc.getRealPath("/");
    }

    public static String getPublicFilePath(ServletContext sc) {
        return getPublicProjectPath(sc) + "/file";
    }

    /**
     * 删除冲突的文件,并将文件创建
     *
     * @param file 要删除的文件
     * @return true 删除成功
     */
    public static void safeDeleteConflictFile(File file) {
        if (file != null) {
            if (file.exists()) {
                try {
                    FileUtils.delete(file);
                    file.createNewFile();
                } catch (IOException e) {
                    log.e(e.getMessage());
                }

            } else {
                try {
                    FileUtils.createParentDirectories(file);
                    file.createNewFile();
                } catch (IOException e) {
                    log.e(e.getMessage());
                }
            }

        }
        if (file == null || !file.exists()) {


            return;
        }
        file.delete();
        FileUtil.createTempFile();

    }


    public static String getFileRawType(InputStream is) {
        if (is == null) {
            return "";
        }
        String key = "";
        try (is) {
            byte[] b = new byte[4];
            int read = is.read(b, 0, b.length);

            key = bytesToHexString(b);
            log.info("文件头信息：" + key);
        } catch (Exception ex) {
            log.info(ex);
        }

        return FileType.PREFIX_FILE_TYPE.get(key);
    }

    public static String getFileType(String type) {
        return FileType.FILE_TYPE_MAP.get(type);
    }

    /*public static String getFileType(InputStream is){
        if (is == null) {
            return "";
        }
        try (is) {
            byte[] b = new byte[4];
            is.read(b, 0, b.length);
        } catch (Exception ex) {
            log.info(ex);
        }

        return FileType.getFileType(type.toLowerCase(Locale.ENGLISH));


    }*/


    public static boolean checkFileHeader(InputStream is, String type) {
        if (is == null) {
            return false;
        }
        String value = "";
        try (is) {
            byte[] b = new byte[4];
            is.read(b, 0, b.length);

            value = bytesToHexString(b);
        } catch (Exception ex) {
            log.info(ex);
            value = "";
        }

        String fileSourceCode = getFileType(type.toLowerCase(Locale.ENGLISH));
        if (fileSourceCode != null) {
            if (fileSourceCode.toLowerCase(Locale.ENGLISH).startsWith(value.toLowerCase()) || value.toLowerCase(Locale.ENGLISH).startsWith(fileSourceCode.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length == 0) {
            return null;
        }
        String hv;
        for (byte b : src) {
            hv = Integer.toHexString(b & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }

        return new String(builder.toString().getBytes(Charset.defaultCharset()), StandardCharsets.ISO_8859_1);
    }

    /**
     * doc:         FEEDFEED
     * platform:    FEEDFEED keystore
     * sd:          30820A9F jks
     * mt:          FEEDFEED
     * nc:          FEEDFEED jks
     * debug.keystore:30820A27
     * zzh.jks:     FEEDFEED
     *
     * @param args 参数
     */
    public static void main(String[] args) {
        File file = new File("file/test.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[4];
            int read = fis.read(b, 0, b.length);
            String keyHeader = bytesToHexString(b);
            System.out.println(keyHeader);
            System.out.println(read);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
